package ycl.scheduled.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 视频工具类
 *
 * @author: YCL
 * @date: 2021-09-01 22:48:42
 */
@Slf4j
public class VideoUtil {


	public static void getFrame(String videoPath, String saveUrl) {
		FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath);
		try {
			grabber.start();
			int length = grabber.getLengthInVideoFrames();
			Frame frame = new Frame();
			int i = 0;
			while (i < length) {
				frame = grabber.grabImage();
				if (++ i > 5 && frame.image != null)
					break;
			}

			Java2DFrameConverter converter = new Java2DFrameConverter();
			BufferedImage image = converter.getBufferedImage(frame);
			int iw = image.getWidth();
			int ih = image.getHeight();

			//缩放
			int w = 800;
			int h = (int) (((double) w / iw) * ih);

			//若是横屏变竖屏
			if (w > h) {
				int t = w;
				w = h;
				h = t;
			}

			File file = new File(saveUrl);
			BufferedImage buffered = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);

			ImageIO.write(buffered, "jpg", file);
		} catch (Exception ignored) {
			log.error("视频图片截取异常");
		} finally {
			try {
				grabber.stop();
			} catch (Exception ignored) {
				log.error("视频图片流关闭异常");
			}
		}
	}
}
